﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.Payments.Controllers
{
    [Area("Payments")]
    public class AreasController : Controller
    {
        protected internal Sysconfig sysConfig;
        public IWebHostEnvironment _env { get; set; }
        public ActionExecutingContext _context { get; set; }
        public IUsersService _users { get; set; }
        public override void OnActionExecuting(ActionExecutingContext context)
        {            
            base.OnActionExecuting(context);
            this._context = context;
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
        }
        /// <summary>
        /// /Web/Error/Index?msg=
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public RedirectResult ToError(string msg)
        {
            return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode(msg));
        }
        #region 会员用户方法==========================================
        /// <summary>
        /// 判断用户是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsUserLogin()
        {
            //如果Session为Null
            if (Request.HttpContext.Session.Get(CMSKeys.SESSION_USER_INFO) != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string username = HttpContext.Request.Cookies[CMSKeys.COOKIE_USER_NAME_REMEMBER];
                string password = HttpContext.Request.Cookies[CMSKeys.COOKIE_USER_PWD_REMEMBER];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    Users model = _users.GetModel(username, password, 0, 0, false);
                    if (model != null)
                    {
                        HttpContext.Session.Set(CMSKeys.SESSION_USER_INFO, ByteConvertHelper.Object2Bytes(model));
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 取得用户信息
        /// </summary>
        public Users GetUserInfo()
        {
            if (IsUserLogin())
            {
                Users model = ByteConvertHelper.Bytes2Object<Users>(Request.HttpContext.Session.Get(CMSKeys.SESSION_USER_INFO));
                if (model != null)
                {
                    //为了能查询到最新的用户信息，必须查询最新的用户资料
                    model = _users.GetModel(model.id);
                    return model;
                }
            }
            return null;
        }
        #endregion
    }
}